<template>
  <a-card class="general-card" title="店员管理" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="showApplyForm"> 账号申请 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :data-list="staffData"
      :columns="columnsTable"
      :methods="sortMethods"
      :enable-pagination="false"
    >
      <template #editor="{ data }">
        <a-button
          v-if="data.checkStatus != '1'"
          type="text"
          status="warning"
          @click="editStaff(data)"
          >编辑</a-button
        >
      </template>
      <template #permission="{ data }">
        <a-button
          v-if="data.checkStatus == '1'"
          type="text"
          @click="showPermissionForm(data)"
          >权限分配</a-button
        >
      </template>
      <template #failSeason="{ data }">
        <a-button
          v-if="data.checkStatus == '2'"
          type="text"
          status="danger"
          @click="showReasonForm(data)"
          >查看原因</a-button
        >
      </template>
    </tablePage>
    <!-- 账号申请表单弹窗 -->
    <a-modal v-model:visible="applyModalVisible" :width="500">
      <template #title> {{ applyModalTitle }} </template>
      <div>
        <a-form
          ref="applyFormRef"
          :model="applyForm"
          :style="{ width: '400px' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item field="name" label="姓名" :rules="[REQUIRED]">
            <a-input v-model="applyForm.name" />
          </a-form-item>
          <a-form-item field="phone" label="手机号" :rules="[REQUIRED]">
            <a-input v-model="applyForm.phone" />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button style="margin-right: 5px" @click="closeApplyForm"
            >取消</a-button
          >
          <a-button type="primary" :loading="loading" @click="submitApplyForm"
            >提交</a-button
          >
        </div>
      </template>
    </a-modal>
    <!-- 审核原因弹窗 -->
    <a-modal
      title-align="start"
      v-model:visible="reasonModalVisible"
      :width="500"
    >
      <template #title> 审核原因 </template>
      <div>
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="拒绝原因">
            {{ reasonForm.failSeason }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button type="primary" @click="closeReasonForm">确定</a-button>
        </div>
      </template>
    </a-modal>
    <!-- 权限分配弹窗 -->
    <a-modal
      v-model:visible="permissionModalVisible"
      :width="500"
      @ok="submitPermission"
    >
      <template #title>权限分配</template>
      <div>
        <a-tree
          ref="treeRef"
          :data="permData"
          :checkable="true"
          :multiple="true"
          v-model:checked-keys="checkedKeys"
          :field-names="{ children: 'children', title: 'title', key: 'id' }"
        />
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button
            style="margin-right: 5px"
            @click="permissionModalVisible = false"
            >取消</a-button
          >
          <a-button type="primary" @click="submitPermission">保存</a-button>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { ColumnsDataRule, MethodsRule } from '@/types/global';
  import { REQUIRED } from '@/utils/validator';
  import tablePage from '@/components/table-pages/index.vue';
  import { staffStatus } from '@/utils/tools';
  import {
    addStaffApplication,
    updateStaffApplication,
    getStaffList,
    getAssistantMenu,
    updateAssistantMenu,
    // 假设这些接口存在，根据实际情况替换
  } from '@/api/staff';
  import { getAllPermissionList } from '@/api/shops';

  const tablePageRef = ref<any>('');
  const applyFormRef = ref<FormInstance>() as any;
  const reasonFormRef = ref<FormInstance>() as any;
  const loading = ref<boolean>(false);

  const applyModalVisible = ref(false);
  const reasonModalVisible = ref(false);
  const permissionModalVisible = ref(false);
  const applyModalTitle = ref<string>('账号申请');

  const treeRef = ref();
  const checkedKeys = ref<string[]>([]);
  const currentStaffId = ref('');
  const permData = ref([]); // 菜单权限数据

  const applyForm = ref({
    id: '',
    name: '',
    phone: '',
  });

  const reasonForm = ref({
    failSeason: '',
  });

  const staffData = ref<any>([]);

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 150,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      width: 180,
    },
    {
      title: '通过时间',
      dataIndex: 'checkTime',
      width: 180,
    },
    {
      title: '状态',
      dataIndex: 'checkStatus',
      slot: true,
      slotData: {
        badge: staffStatus,
      },
    },
  ];
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 200,
    methods: [
      {
        title: '编辑',
        callback: 'editor',
        slot: true,
        slotTemplate: 'editor',
      },
      {
        title: '权限分配',
        callback: 'permission',
        slot: true,
        slotTemplate: 'permission',
      },
      {
        title: '查看原因',
        callback: 'failSeason',
        slot: true,
        slotTemplate: 'failSeason',
      },
    ],
  };

  // 显示账号申请表单
  const showApplyForm = () => {
    applyModalTitle.value = '账号申请';
    applyForm.value = { id: '', name: '', phone: '' };
    applyModalVisible.value = true;
  };

  // 关闭账号申请表单
  const closeApplyForm = () => {
    applyFormRef.value.resetFields();
    applyModalVisible.value = false;
  };

  // 获取店员列表
  const getData = () => {
    getStaffList().then((res) => {
      if (res.data.success) {
        staffData.value = res.data.result.records.map(
          (item: any, index: number) => ({
            ...item,
            index: index + 1,
          })
        );
      }
    });
  };

  // 提交账号申请
  const submitApplyForm = async () => {
    loading.value = true;
    try {
      if (applyForm.value.id) {
        const res = await updateStaffApplication(applyForm.value);
        if (!res.data.success) {
          return;
        }
        Message.success('编辑成功');
      } else {
        const res = await addStaffApplication(applyForm.value);
        if (!res.data.success) {
          return;
        }
        Message.success('申请成功');
      }
      closeApplyForm();
      getData();
    } catch (error) {
    } finally {
      loading.value = false;
    }
  };

  // 编辑店员信息
  const editStaff = (data: any) => {
    applyModalTitle.value = '编辑信息';
    applyForm.value = { ...data };
    applyModalVisible.value = true;
  };

  // 显示审核原因表单
  const showReasonForm = (data: any) => {
    reasonForm.value = { failSeason: data.failSeason };
    reasonModalVisible.value = true;
  };

  // 关闭审核原因表单
  const closeReasonForm = () => {
    // reasonFormRef.value.resetFields();
    reasonModalVisible.value = false;
  };

  // 关闭权限分配表单
  const closePermissionForm = () => {
    permissionModalVisible.value = false;
  };

  // 显示权限分配表单
const showPermissionForm = (data: any) => {
    currentStaffId.value = data.id;
    getAssistantMenu(data.id).then((res) => {
      if (res.data.success) {
        checkedKeys.value = res.data.result.map((item: any) => String(item.menuId));
      }
    });
    permissionModalVisible.value = true;
};


  // 提交权限分配
  const submitPermission = () => {
    const selectedNodes = treeRef.value.getCheckedNodes();
    const menuIds = selectedNodes.map((node: any) => node.id);
    const data = menuIds.map((item: any) => ({ menuId: item, assistantId: currentStaffId.value, isSuper: 1 }));

    updateAssistantMenu(currentStaffId.value, data).then((res) => {
      if (res.data.success) {
        Message.success('权限分配成功');
        permissionModalVisible.value = false;
      }
    });
  };
  const getPermList = () => {
    getAllPermissionList().then((res) => {
      if (res.data.success) {
        permData.value = res.data.result.map((item: any) => {
          delete item.icon;
          return item;
        });
      }
    });
  };

  onMounted(() => {
    getData();
    getPermList();
  });
</script>
